package com.teamall.web.app.controller;

import com.teamall.framework.exception.BaseAppException;
import com.teamall.framework.util.MD5Utils;
import com.teamall.framework.util.MessageResourceUtils;
import com.teamall.framework.util.Utils;
import com.teamall.web.app.vo.AppUserVO;
import com.teamall.web.sys.db.po.SysPhotoPO;
import com.teamall.web.sys.db.po.SysUserPO;
import com.teamall.web.sys.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * ${DESCRIPTION}
 *
 * @author
 * @create 2017-08-13 18:19
 **/
@Controller
@RequestMapping("/app")
public class AppSignLogin {
    @Autowired
    private ISysUserService sysUserService;

    @RequestMapping("/sign")
    @ResponseBody
    public Map sign(HttpServletRequest request, String mobile) throws BaseAppException{
        Map resultMap = new HashMap();
        String time = request.getHeader("time");
        String sign = request.getHeader("sign");
        String sys_key = request.getHeader("sys_key");
        if(StringUtils.isEmpty(mobile)||StringUtils.isEmpty(time)||StringUtils.isEmpty(sign)){
            resultMap.put("code","8002");
            resultMap.put("msg","参数不正确");
            return resultMap;
        }
        String signstr = this.md5Sign(sys_key,mobile);
        if(!sign.equals(signstr)){
            resultMap.put("code","8001");
            resultMap.put("msg","鉴权失败");
            return resultMap;
        }
        AppUserVO vo = sysUserService.userLogin(mobile);
        if(Utils.notEmpty(vo)){
            resultMap.put("code","0");
            resultMap.put("msg","成功");
            Map voMap = new HashMap();
            voMap.put("token",vo.getToken());
            voMap.put("create_date",new Date());
            voMap.put("user_id",vo.getUserId());
            voMap.put("town_id",vo.getTownId());
            voMap.put("village_id",vo.getVillageId());
            resultMap.put("data",voMap);
        }else{
            resultMap.put("code","9000");
            resultMap.put("msg","手机号码不存在");
        }
        return resultMap;
    }
    private String md5Sign(String sysKe,String mobile){
        String sign = MessageResourceUtils.getMessage("sign");
        String signStr = sysKe + sign  + mobile;
        return MD5Utils.MD5(signStr).toLowerCase();
    }

}
